import global from './global.js'
import {
    goAppList,
    toast
} from './util.js'
import {
    getUserOpenId,
    getUserInfo
} from '../api/app.js'
class User {
    constructor() {
        this.init()
    }
    init() {
        this.isOpenAlipayAccount = true // 是否开通支付宝
        this.system = {} // 当前用户手机信息
        this.openid = '' // 用户openID
        this.unionid = '' // 用户unionid
        this.session_key = '' // 微信session
        this.userId = '' // 用户唯一ID
        this.isAdmin = false // 是否管理员
        this.isSuperAdmin = false // 是否超级管理员
        this.userName = '' // 用户名称
        this.phoneNum = '' // 手机号码
        this.companyName = '' // 公司名称
        this.companyId = '' // 公司ID
        this.position = '' // 职位
        this.avatarUrl = '' // 头像url
        this.waiting = true // 控制位，是否正在登陆中
        this.auditStatus = false // 是否开户（显示余额）
        this.companyIdList = [] // 用户公司列表
        this.isAttention = false // 是否关注公众号
        this.quickProject = null // 是否开通快速发薪项目
        this.isOpenWesure = false,
        this.isOpenPeriodInsur = false
        this.insureCompanyType = '' // 保险公司类型
        this.insureTypeReplace = [],
        this.insureType = []
        this.signInMode = 0,
        this.companyAbbreviation = '' // 公司简称
        this.createUserId = '',
        this.balanceRemind = '', // 是否开启 余额不足提示 0 是不开启 其他数额 是开启    
        this.expireStatus = false,
        this.isOpenPaySalary = true // 是否开通发薪
        this.isPayActivity = true // 是否显示首页活动弹窗
        this.isWorkActivity = true
        this.mchid = ''
        this.bankName = ''
        this.bankNo = ''
        this.openBank = ''
        this.bankLogo = ''
        this.receiptId = ''
        this.isForbidInsure = true
        this.mpOpenid = ''
        this.hasOpenid = false
        this.channelName = ''
        this.isSeatAdmin = null
        this.cutOffTime = ''
        this.wechatMchId = ''
        this.isOpenWechatPay = false
    }
    /**
     * 重新登录/首次登录
     * @returns {Promise<user>}
     */
    reLogin() {
        return new Promise((reslove, reject) => {
            const t = this
            wx.login({
                success(res) {
                    console.log('获取到用户code:' + res.code)
                    if (res.code) {
                        // 发起网络请求
                        getUserOpenId({
                            appId: global.appId,
                            code: res.code
                        }).then((res) => {
                            t.session_key = res.sessionKey
                            t.openid = res.openid
                            t.unionid = res.unionid
                            const token = res.token
                            getUserInfo({
                                openId: res.openid
                            }).then(res => {
                                t.waiting = false
                                if (res) {
                                    console.log(res, 'user.isAdmin')
                                    t.isOpenAlipayAccount = !!res.params.isOpenAlipayAccount
                                    t.cutOffTime = res.params.cutOffTime
                                    t.isSeatAdmin = res.isSeatAdmin
                                    t.userId = res.userId
                                    t.phoneNum = res.phone
                                    t.companyName = res.params.companyName
                                    t.companyId = res.companyId
                                    t.position = res.position
                                    t.userName = res.userName
                                    t.avatarUrl = res.userHeadUrl
                                    t.isAdmin = res.isAdmin
                                    t.auditStatus = res.params.auditStatus
                                    t.companyIdList = res.params.companyIdList
                                    t.hasPassword = res.params.hasPassword
                                    t.isSuperAdmin = res.params.isSuperAdmin
                                    t.isAttention = res.isAttention
                                    t.quickProject = res.params.quickProject
                                    t.isOpenWesure = res.params.isOpenWesure
                                    t.insureCompanyType = res.params.insureCompanyType
                                    t.insureTypeReplace = res.params.insureTypeReplace
                                    t.isOpenPeriodInsur = res.params.isOpenPeriodInsur
                                    t.insureType = res.params.insureType
                                    t.signInMode = res.params.signInMode // 1 刷脸  0 拍照
                                    t.companyAbbreviation = res.params.companyAbbreviation || ''
                                    global.token = token
                                    t.createUserId = res.createUserId
                                    t.balanceRemind = res.params.balanceRemind
                                    t.isOpenPaySalary = !!res.params.isOpenPaySalary
                                    t.mchid = res.params.bankInfo.wechatMchId,
                                    t.bankName = res.params.bankInfo.bankName,
                                    t.bankNo = res.params.bankInfo.bankNo,
                                    t.openBank = res.params.bankInfo.openBank
                                    t.bankLogo = res.params.bankInfo.bankLogo
                                    t.receiptId = res.params.bankInfo.receiptId
                                    t.wechatMchId = res.params.bankInfo.wechatMchId
                                    t.isOpenWechatPay = res.params.isOpenWechatPay
                                    t.isForbidInsure = res.params.isForbidInsure
                                    t.mpOpenid = res.mpOpenid
                                    t.hasOpenid = res.mpOpenid!==null && res.mpOpenid!==0 && res.mpOpenid!=='0' 
                                    t.channelName = res.params.bankInfo.channelName
                                    reslove(t)
                                } else {
                                    reject()
                                }
                            })
                        })

                    }
                },
                fail() {
                    this.waiting = false
                    toast('获取用户信息失败', 'error')
                    reject()
                }
            })
        })
    }

    /**
     * 登录，如果已经登录将直接返回用户信息
     * @returns {Promise<user>}
     */
    login() {
        // 如果已登录（使用Promise.relove()需要开增强编译）
        if (this.userId) {
            this.waiting = false
            return new Promise((reslove) => {
                reslove(this)
            })
        }
        // 未登录
        return this.reLogin()
    }

    /**
     * 等待登录
     * @returns {Promise<user>}
     */
    waitLogin() {
        return new Promise((reslove, reject) => {
            const func = ()=>{
                if (!this.waiting) {
                    clearInterval(wait)
                    if (this.userId) {
                        reslove(this)
                    } else {
                        reject()
                    }
                }
            }
            const wait = setInterval(func, 500)
            func()
        })
    }

    /**
     * 前往用户注册界面
     */
    goRegister() {
        goAppList([
            {
                url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5c6159f72a9705f&redirect_uri=https://front.51zidan.com/mini-auth/pay.html?' + encodeURIComponent('openid=' + this.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
                time: 3000
            },
            {
                url: 'applet::/pages/login/login',
                type: 'redirectTo'
            }
        ])
    }
}
const user = new User()
export default user